package com.tsfyun.scm.service.impl.logistics;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.security.SecurityUtil;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.scm.dto.logistics.ConveyanceDTO;
import com.tsfyun.scm.dto.logistics.ConveyanceQTO;
import com.tsfyun.scm.entity.logistics.Conveyance;
import com.tsfyun.scm.mapper.logistics.ConveyanceMapper;
import com.tsfyun.scm.service.logistics.IConveyanceService;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.util.TsfWeekendSqls;
import com.tsfyun.scm.vo.logistics.SimpleConveyanceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 * @since 2020-03-20
 */
@Slf4j
@Service
public class ConveyanceServiceImpl extends ServiceImpl<Conveyance> implements IConveyanceService {

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private ConveyanceMapper conveyanceMapper;

    @Override
    public List<Conveyance> list(@NonNull Long transportSupplierId) {
        Conveyance conveyance = new Conveyance();
        conveyance.setTransportSupplierId(transportSupplierId);
        return super.list(conveyance);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addBatch(Long transportSupplierId, List<ConveyanceDTO> conveyances) {
        if(CollUtil.isEmpty(conveyances)) {
            return;
        }
        long setDefaultCount = conveyances.stream().filter(r-> Objects.equals(r.getIsDefault(),Boolean.TRUE)).count();
        if(setDefaultCount < 1) {
            //如果没有一个默认的，则设置第一个为默认的
            conveyances.get(0).setIsDefault(Boolean.TRUE);
        } else if(setDefaultCount > 1) {
            //如果设置了多个默认的，则将除首个设置的默认外全部置为非默认，保证永远只有一个默认的
            boolean findFirstDefault = false;
            for(int i = 0,length = conveyances.size();i < length; i++) {
                if(findFirstDefault && Objects.equals(conveyances.get(i).getIsDefault(),Boolean.TRUE)) {
                    conveyances.get(i).setIsDefault(Boolean.FALSE);
                }
                if(!findFirstDefault && Objects.equals(conveyances.get(i).getIsDefault(),Boolean.TRUE)) {
                    findFirstDefault = true;
                }
            }
        }
        List<Conveyance> conveyanceList = Lists.newArrayList();
        conveyances.stream().forEach(dto->{
            Conveyance r = new Conveyance();
            r.setId(snowflake.nextId());
            r.setTransportSupplierId(transportSupplierId);
            //去特殊字符
            r.setConveyanceNo(StringUtils.removeSpecialSymbol(dto.getConveyanceNo()));
            r.setConveyanceNo2(StringUtils.removeSpecialSymbol(dto.getConveyanceNo2()));
            r.setCustomsRegNo(StringUtils.removeSpecialSymbol(dto.getCustomsRegNo()));
            r.setDriver(StringUtils.removeSpecialSymbol(dto.getDriver()));
            r.setDriverNo(StringUtils.removeSpecialSymbol(dto.getDriverNo()));
            r.setDriverTel(StringUtils.removeSpecialSymbol(dto.getDriverTel()));
            r.setHead(StringUtils.removeSpecialSymbol(dto.getHead()));
            r.setHeadFax(StringUtils.removeSpecialSymbol(dto.getHeadFax()));
            r.setHeadNo(StringUtils.removeSpecialSymbol(dto.getHeadNo()));
            r.setHeadTel(StringUtils.removeSpecialSymbol(dto.getHeadTel()));
            r.setDisabled(dto.getDisabled());
            r.setIsDefault(dto.getIsDefault());
            r.setDateCreated(LocalDateTime.now());
            r.setDateUpdated(r.getDateCreated());
            r.setCreateBy(SecurityUtil.getCurrentPersonIdAndName());
            r.setUpdateBy(r.getCreateBy());
            conveyanceList.add(r);
        });
        super.savaBatch(conveyanceList);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByTransportSupplierId(Long transportSupplierId) {
        conveyanceMapper.deleteByExample(Example.builder(Conveyance.class).where(TsfWeekendSqls.<Conveyance>custom().andEqualTo(false,Conveyance::getTransportSupplierId,transportSupplierId)).build());
    }

    @Override
    public int countByTransportSupplierId(Long transportSupplierId) {
        return conveyanceMapper.selectCountByExample(Example.builder(Conveyance.class).where(TsfWeekendSqls.<Conveyance>custom().andEqualTo(false,Conveyance::getTransportSupplierId,transportSupplierId)).build());
    }

    @Override
    public List<SimpleConveyanceVO> select(ConveyanceQTO qto) {
        List<Conveyance> conveyances =  conveyanceMapper.selectByExample(Example.builder(Conveyance.class).where(TsfWeekendSqls.<Conveyance>custom().andEqualTo(true,Conveyance::getTransportSupplierId,qto.getTransportSupplierId())
            .andLike(true,Conveyance::getConveyanceNo,qto.getConveyanceNo())
            .andLike(true,Conveyance::getConveyanceNo2,qto.getConveyanceNo2())
            .andLike(true,Conveyance::getDriver,qto.getDriver())
            .andEqualTo(false,Conveyance::getDisabled,Boolean.FALSE)).build());
        //按是否默认和修改时间排序
        conveyances = conveyances.stream().sorted(Comparator.comparing(Conveyance::getIsDefault).thenComparing(Conveyance::getDateUpdated).reversed()).collect(Collectors.toList());
        return beanMapper.mapAsList(conveyances,SimpleConveyanceVO.class);
    }
}
